#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <grp.h>
#include <fcntl.h>
#include <readline/readline.h>
#include <readline/history.h>

char fis[20][20];

void cmd_chgrp(char *comm)
{
	char *c,*y,*x,linie[100];
	uid_t owner;
	gid_t gr;
	char *grname;
	int i=1,j,ok_v,ok_R,ch,rez;
	c = strtok (comm, " ");
	while ((c = strtok (NULL, " ")) != NULL)
	{
		if (strcmp (c, "--help") == 0)
		{
			FILE *h = fopen ("help_chgrp.txt", "r");
			while ((ch = fgetc (h)) != EOF)
				fputc (ch, stdout);
			fclose (h);
			return;
		}
		if (strcmp (c, "-v") == 0)
			ok_v = 1;
		else if (strcmp (c, "-R") == 0)
			ok_R = 1;
		else if ((strcmp (c, "-Rv") == 0) || (strcmp (c, "-vR") == 0)) 
		{
			ok_v = 1;
			ok_R = 1;
		}
		else if (access (c, F_OK) == 0)
		{
			struct stat stat_buf;
			if (stat (c, &stat_buf) == 0)
				if (S_ISREG (stat_buf.st_mode) || S_ISDIR (stat_buf.st_mode))
				{					
					strcpy (fis[i], c);
					i++;
				}
		}
		else
		{
			grname = (char *) malloc (sizeof (char) * strlen (c));
			strcpy (grname, c);
			int f = open ("/etc/passwd", O_RDONLY);
			while ((ch = read (f, linie, 100)) > 0)
			{
				x = strtok (linie, "\n");
				do
				{
					y = strtok (x, ":");
					if (strcmp (y, grname) == 0)
					{
						y = strtok (NULL, ":");
						owner = (uid_t)strtok (NULL, ":");
						gr = (gid_t)strtok (NULL, ":");
					}
				} while ((x = strtok (NULL, "\n")) != NULL);
			}
		}
	}
	i--;
	if (gr == 0)
		fprintf (stderr, "group not exist\n");
	else if (i)
		for (j = 1; j <= i; j++)
		{
			rez = chown(fis[i],owner,gr); 
			fprintf (stderr, "rez = %d\n", rez);
		}
	else
		fprintf (stderr, "error!\n");
/*	x = getgrgid (101);
	fputs (x->gr_name, stderr);
	fprintf (stderr, "\n%d \n", x->gr_gid);
	owner = getuid();
	fprintf (stderr, "owner = %\n", owner);
	fprintf (stderr, " perms? \n");*/
}

int main()
{
	char *comm;
	comm = readline ("$: ");
	cmd_chgrp(comm);
	return 0;
}
